/**
 * 班级点名系统的主要JavaScript文件
 * @author Ysz
 * @version 1.0.0
 */

// 全局变量和状态管理
const state = {
    names: JSON.parse(localStorage.getItem('rollCallNames')) || [
    '李思嘉', '崔致允', '孙梓埝', '杨朝晖', '杨洋', 
    '侯琳汐', '徐梓玥', '闫诗涵', '万夏', '卞晨昊', 
    '张睿宸', '孙海锋', '王博远', '孔诺熠阳', '吴颖', 
    '蔡梓嫣', '郭昕睿', '樊婧怡', '齐子轩', '高欣怡', 
    '罗瑞阳', '李金宗', '杨浩宸', '赵语', '刘明朗', 
    '杨浩宇', '胡龙豚', '刘梦焓', '卫欣晨','朱宝伊'
    ],
    selectedPool: new Set(), // 当前选中的抽取池
    rollInterval: null,
    isRolling: false,
    selectedCount: 1,
    selectedNames: [],
    fireworksInterval: null
};

// DOM 元素缓存
const elements = {
    startRollBtn: document.getElementById('startRoll'),
    settingsBtn: document.getElementById('settingsBtn'),
    settingsModal: document.getElementById('settingsModal'),
    closeModalBtn: document.getElementById('closeModal'),
    nameList: document.getElementById('nameList'),
    newNameInput: document.getElementById('newName'),
    addNameBtn: document.getElementById('addName'),
    avatarContainer: document.getElementById('avatarContainer'),
    slotWrapper: document.getElementById('slotWrapper'),
    numberBtns: document.querySelectorAll('.number-btn'),
    poolSettingsBtn: document.getElementById('poolSettingsBtn'),
    poolSettingsModal: document.getElementById('poolSettingsModal'),
    closePoolModal: document.getElementById('closePoolModal'),
    selectAllBtn: document.getElementById('selectAllBtn'),
    studentSearch: document.getElementById('studentSearch'),
    studentGrid: document.getElementById('studentGrid'),
    selectedCountDisplay: document.getElementById('selectedCount')
};

// 颜色配置
const colorSchemes = {
    front: [
        ['#4A90E2', '#67B8F7'], ['#8E44AD', '#9B59B6'], 
        ['#2ECC71', '#87D37C'], ['#E67E22', '#F4A460'],
        ['#16A085', '#36D7B7'], ['#9B27AF', '#E040FB'],
        ['#00BCD4', '#26C6DA'], ['#3F51B5', '#5C6BC0'],
        ['#009688', '#26A69A'], ['#F44336', '#EF5350']
    ],
    back: [
        ['#67B8F7', '#4A90E2'], ['#9B59B6', '#8E44AD'],
        ['#87D37C', '#2ECC71'], ['#F4A460', '#E67E22'],
        ['#36D7B7', '#16A085'], ['#E040FB', '#9B27AF'],
        ['#26C6DA', '#00BCD4'], ['#5C6BC0', '#3F51B5'],
        ['#26A69A', '#009688'], ['#EF5350', '#F44336']
    ],
    fireworks: ['#ff8426', '#ffb26b', '#ff5722', '#ffd700', '#ff4081', '#FFA500', '#FFD700']
};

// 工具函数
const utils = {
    getLastCharacter: name => name.charAt(name.length - 1),
    
    getRandomGradient: (isBack = false) => {
        const colors = isBack ? colorSchemes.back : colorSchemes.front;
    const randomPair = colors[Math.floor(Math.random() * colors.length)];
    return `linear-gradient(45deg, ${randomPair[0]}, ${randomPair[1]})`;
    },
    
    getRandomNames: count => {
        const availableNames = state.names.filter(name => state.selectedPool.has(name));
        if (availableNames.length === 0) return [];
        const shuffled = [...availableNames].sort(() => 0.5 - Math.random());
        return shuffled.slice(0, count);
    },
    
    saveNames: () => localStorage.setItem('rollCallNames', JSON.stringify(state.names)),
    
    saveSelectedPool: () => {
        localStorage.setItem('selectedPool', JSON.stringify([...state.selectedPool]));
    },
    
    loadSelectedPool: () => {
        const saved = localStorage.getItem('selectedPool');
        if (saved) {
            state.selectedPool = new Set(JSON.parse(saved));
        } else {
            state.selectedPool = new Set(state.names); // 默认全选
        }
    },
    
    updateSelectedCount: () => {
        if (elements.selectedCountDisplay) {
            elements.selectedCountDisplay.textContent = state.selectedPool.size;
        }
        // 更新全选按钮状态
        if (elements.selectAllBtn) {
            const allSelected = state.selectedPool.size === state.names.length;
            elements.selectAllBtn.innerHTML = `<i class="far${allSelected ? ' fas' : ''} fa-square${allSelected ? '-check' : ''}"></i> ${allSelected ? '取消全选' : '全选'}`;
        }
        
        // 更新选择人数按钮的显示状态
        const availableCount = state.selectedPool.size;
        elements.numberBtns.forEach(btn => {
            const count = parseInt(btn.dataset.count);
            if (count > availableCount) {
                btn.style.display = 'none';
                if (btn.classList.contains('active')) {
                    // 如果当前选中的人数大于可用人数，自动选择第一个可用的按钮
                    const firstAvailableBtn = Array.from(elements.numberBtns)
                        .find(b => parseInt(b.dataset.count) <= availableCount);
                    if (firstAvailableBtn) {
                        btn.classList.remove('active');
                        firstAvailableBtn.classList.add('active');
                        state.selectedCount = parseInt(firstAvailableBtn.dataset.count);
                        actions.initializeSlotMachine();
                    }
                }
            } else {
                btn.style.display = '';
            }
        });
    }
};

// UI 组件创建函数
const createElements = {
    avatar: (name, isBack = false) => {
        const avatar = document.createElement('div');
        avatar.className = isBack ? 'avatar-back' : 'avatar-front';
        avatar.textContent = utils.getLastCharacter(name);
        avatar.style.background = utils.getRandomGradient(isBack);
        return avatar;
    },
    
    slotItem: (name, isPlaceholder = false) => {
    const item = document.createElement('div');
        item.className = `slot-item${isPlaceholder ? ' placeholder-item' : ''}`;
    
    const avatarContainer = document.createElement('div');
    avatarContainer.className = 'avatar';
    
        const avatarFront = createElements.avatar(name || '?');
        const avatarBack = createElements.avatar(name || '?', true);
        
        avatarContainer.append(avatarFront, avatarBack);
    
    const nameSpan = document.createElement('div');
    nameSpan.className = 'name';
        nameSpan.textContent = name || '待抽取';
    
        item.append(avatarContainer, nameSpan);
    return item;
}
};

// 动画效果
const animations = {
    createFireworks: () => {
        clearInterval(state.fireworksInterval);
        const container = document.querySelector('.fireworks-container');
        container.innerHTML = '';
        
        const createParticles = (x, y) => {
            const particleCount = 30;
            const angleStep = (2 * Math.PI) / particleCount;
            const colors = ['#FFD700', '#FF6B6B', '#4CAF50', '#FF1493', '#00BFFF', '#FFA500', '#9B59B6'];
            
            for (let i = 0; i < particleCount; i++) {
                const particle = document.createElement('div');
                particle.className = 'firework';
                const color = colors[Math.floor(Math.random() * colors.length)];
                
                const angle = angleStep * i;
                const velocity = 150 + Math.random() * 100;
                const dx = Math.cos(angle) * velocity;
                const dy = Math.sin(angle) * velocity;
                
                particle.style.cssText = `
                    left: ${x}px;
                    top: ${y}px;
                    --x: ${x}px;
                    --y: ${y}px;
                    --dx: ${dx}px;
                    --dy: ${dy}px;
                    --color: ${color};
                `;
                
                container.appendChild(particle);
                setTimeout(() => particle.remove(), 1500);
            }
        };
        
        const createFirework = () => {
            // 计算屏幕中心区域的随机位置
            const centerX = window.innerWidth / 2;
            const centerY = window.innerHeight / 2;
            const spreadX = window.innerWidth * 0.4; // 水平扩散范围
            const spreadY = window.innerHeight * 0.4; // 垂直扩散范围
            
            // 在中心区域随机生成烟花
            const x = centerX + (Math.random() - 0.5) * spreadX;
            const y = centerY + (Math.random() - 0.5) * spreadY;
            
            // 直接在目标位置创建粒子，不使用火箭动画
            createParticles(x, y);
        };
        
        // 初始发射多个烟花
        for (let i = 0; i < 3; i++) {
            setTimeout(createFirework, i * 200);
        }
        
        // 持续发射烟花
        state.fireworksInterval = setInterval(createFirework, 800);
    },
    
    stopFireworks: () => {
        clearInterval(state.fireworksInterval);
        document.querySelector('.fireworks-container').innerHTML = '';
    }
};

// 主要功能函数
const actions = {
    initializeUI: () => {
        elements.nameList.innerHTML = '';
        document.getElementById('modalTotalCount').textContent = state.names.length;
        
        state.names.forEach((name, index) => {
            const li = document.createElement('li');
            const studentInfo = document.createElement('div');
            studentInfo.className = 'student-info';
            
            const avatar = createElements.avatar(name);
            avatar.className = 'student-avatar';
    
    const nameSpan = document.createElement('div');
            nameSpan.className = 'student-name';
            nameSpan.textContent = name;
            
            studentInfo.append(avatar, nameSpan);
            
            const actionButtons = document.createElement('div');
            actionButtons.className = 'action-buttons';
            actionButtons.innerHTML = `
                <button class="action-btn edit-btn" onclick="actions.editName(${index})">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="action-btn delete-btn" onclick="actions.deleteName(${index})">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            
            li.append(studentInfo, actionButtons);
            elements.nameList.appendChild(li);
        });
        
        actions.initializeAvatarWall();
    },
    
    initializeAvatarWall: () => {
        elements.avatarContainer.innerHTML = '';
        state.names.forEach((name, index) => {
            const avatar = document.createElement('div');
            avatar.className = 'avatar';
            avatar.dataset.name = name;
            avatar.textContent = utils.getLastCharacter(name);
            avatar.style.background = utils.getRandomGradient();
            avatar.style.animationDelay = `${index * 0.1}s`;
            elements.avatarContainer.appendChild(avatar);
        });
    },
    
    initializeSlotMachine: () => {
        if (!elements.slotWrapper) return;
        
        elements.slotWrapper.innerHTML = '';
        elements.slotWrapper.dataset.count = state.selectedCount;
        
        for (let i = 0; i < state.selectedCount; i++) {
            const item = createElements.slotItem(null, true);
            item.style.animation = 'itemChange 0.5s ease-in-out';
            item.style.animationDelay = `${i * 0.1}s`;
            elements.slotWrapper.appendChild(item);
        }
        
    setTimeout(() => {
            elements.slotWrapper.querySelectorAll('.slot-item').forEach(item => {
            item.style.animation = '';
            item.style.animationDelay = '';
        });
        }, 500 + (state.selectedCount - 1) * 100);
    },
    
    toggleRoll: () => {
        if (state.names.length === 0) {
        alert('请先添加小朋友的名字！');
        return;
    }

        if (state.selectedCount > state.names.length) {
            alert(`当前班级只有 ${state.names.length} 位小朋友，无法抽取 ${state.selectedCount} 人！`);
        return;
    }

    const slotMachine = document.querySelector('.slot-machine');

        if (state.isRolling) {
            clearInterval(state.rollInterval);
            elements.startRollBtn.innerHTML = `
            <div class="roll-btn-content">
                    <div class="btn-icon"><i class="fas fa-random"></i></div>
                <span class="btn-text">开始抽取</span>
                <div class="btn-ripple"></div>
            </div>`;
            state.isRolling = false;
            state.selectedNames = utils.getRandomNames(state.selectedCount);
        slotMachine.classList.remove('rolling');
        
        setTimeout(() => {
                actions.updateSlotMachine(state.selectedNames);
            document.querySelectorAll('.slot-item').forEach((item, index) => {
                setTimeout(() => {
                    item.classList.add('winner-item');
                        if (index === state.selectedNames.length - 1) {
                            animations.createFireworks();
                    }
                }, index * 200);
            });
        }, 100);
        
            actions.updateAvatarWallSelection(state.selectedNames);
    } else {
            animations.stopFireworks();
            elements.startRollBtn.innerHTML = `
            <div class="roll-btn-content">
                    <div class="btn-icon"><i class="fas fa-random"></i></div>
                <span class="btn-text">停止</span>
                <div class="btn-ripple"></div>
            </div>`;
            state.isRolling = true;
        slotMachine.classList.add('rolling');
        
            let speed = 50;
        let slowDownStart = false;
        let currentIndex = 0;
            const shuffledQueue = [...state.names].sort(() => 0.5 - Math.random());
        let startPosition = Math.floor(Math.random() * shuffledQueue.length);
        
            const roll = () => {
            const currentNames = [];
                for (let i = 0; i < state.selectedCount; i++) {
                const position = (startPosition + i) % shuffledQueue.length;
                currentNames.push(shuffledQueue[position]);
            }
                actions.updateSlotMachine(currentNames);
                startPosition = (startPosition + 1) % shuffledQueue.length;
            };
            
            state.rollInterval = setInterval(() => {
                roll();
            currentIndex++;
            
            if (currentIndex > 20 && !slowDownStart) {
                slowDownStart = true;
                speed = 100;
                    clearInterval(state.rollInterval);
                    state.rollInterval = setInterval(() => {
                        roll();
                    if (speed < 300) {
                        speed += 20;
                            clearInterval(state.rollInterval);
                            state.rollInterval = setInterval(roll, speed);
                    }
                }, speed);
            }
        }, speed);
    }
    },
    
    updateSlotMachine: displayNames => {
        elements.slotWrapper.innerHTML = '';
        elements.slotWrapper.dataset.count = state.selectedCount;
        displayNames.forEach(name => {
            elements.slotWrapper.appendChild(createElements.slotItem(name));
        });
    },
    
    updateAvatarWallSelection: selectedNames => {
    document.querySelectorAll('.avatar-container .avatar').forEach(avatar => {
            avatar.classList.toggle('selected', selectedNames.includes(avatar.dataset.name));
        });
    },
    
    editName: index => {
        const newName = prompt('请输入新的名字：', state.names[index]);
        if (newName?.trim()) {
            state.names[index] = newName.trim();
            actions.initializeUI();
            utils.saveNames();
        }
    },
    
    deleteName: index => {
        if (confirm('确定要删除这个小朋友吗？')) {
            state.names.splice(index, 1);
            actions.initializeUI();
            utils.saveNames();
        }
    },
    
    addNewName: () => {
        const newName = elements.newNameInput.value.trim();
        if (newName) {
            state.names.push(newName);
            elements.newNameInput.value = '';
            actions.initializeUI();
            utils.saveNames();
        }
    },
    
    initializePoolSettings: () => {
        utils.loadSelectedPool();
        elements.studentGrid.innerHTML = '';
        
        state.names.forEach(name => {
            const card = document.createElement('div');
            card.className = `student-card${state.selectedPool.has(name) ? ' selected' : ''}`;
            
            const avatar = document.createElement('div');
            avatar.className = 'avatar';
            avatar.style.background = utils.getRandomGradient();
            avatar.textContent = utils.getLastCharacter(name);
            
            const nameSpan = document.createElement('div');
            nameSpan.className = 'name';
            nameSpan.textContent = name;
            
            card.append(avatar, nameSpan);
            
            card.addEventListener('click', () => {
                if (state.selectedPool.has(name)) {
                    state.selectedPool.delete(name);
                    card.classList.remove('selected');
                } else {
                    state.selectedPool.add(name);
                    card.classList.add('selected');
                }
                utils.saveSelectedPool();
                utils.updateSelectedCount();
            });
            
            elements.studentGrid.appendChild(card);
        });
        
        utils.updateSelectedCount();
    },
    
    toggleSelectAll: () => {
        const allSelected = state.selectedPool.size === state.names.length;
        
        elements.studentGrid.querySelectorAll('.student-card').forEach(card => {
            const name = card.querySelector('.name').textContent;
            if (allSelected) {
                state.selectedPool.delete(name);
                card.classList.remove('selected');
            } else {
                state.selectedPool.add(name);
                card.classList.add('selected');
            }
        });
        
        utils.saveSelectedPool();
        utils.updateSelectedCount();
    },
    
    filterStudents: (searchText) => {
        const normalizedSearch = searchText.toLowerCase();
        elements.studentGrid.querySelectorAll('.student-card').forEach(card => {
            const name = card.querySelector('.name').textContent;
            card.style.display = name.toLowerCase().includes(normalizedSearch) ? '' : 'none';
        });
    },
    
    closePoolSettingsModal: () => {
        if (state.selectedPool.size === 0) {
            if (confirm('至少选择一位同学，确定关闭后为全班抽取')) {
                // 全选所有学生
                state.selectedPool = new Set(state.names);
                utils.saveSelectedPool();
                utils.updateSelectedCount();
                elements.poolSettingsModal.classList.remove('active');
            }
        } else {
            elements.poolSettingsModal.classList.remove('active');
        }
    }
};

// 事件监听器设置
const setupEventListeners = () => {
    elements.startRollBtn.addEventListener('click', actions.toggleRoll);
    elements.settingsBtn.addEventListener('click', () => elements.settingsModal.classList.add('active'));
    elements.closeModalBtn.addEventListener('click', () => elements.settingsModal.classList.remove('active'));
    elements.addNameBtn.addEventListener('click', actions.addNewName);
    elements.newNameInput.addEventListener('keypress', e => {
        if (e.key === 'Enter') actions.addNewName();
    });
    
    elements.numberBtns.forEach(btn => {
    btn.addEventListener('click', () => {
            elements.numberBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
            state.selectedCount = parseInt(btn.dataset.count);
            actions.initializeSlotMachine();
        });
    });
    
    elements.settingsModal.addEventListener('click', e => {
        if (e.target === elements.settingsModal) {
            elements.settingsModal.classList.remove('active');
        }
    });
    
    elements.poolSettingsBtn.addEventListener('click', () => {
        elements.poolSettingsModal.classList.add('active');
        actions.initializePoolSettings();
    });
    
    elements.closePoolModal.addEventListener('click', actions.closePoolSettingsModal);
    
    elements.selectAllBtn.addEventListener('click', actions.toggleSelectAll);
    
    elements.studentSearch.addEventListener('input', (e) => {
        actions.filterStudents(e.target.value);
    });
    
    elements.poolSettingsModal.addEventListener('click', e => {
        if (e.target === elements.poolSettingsModal) {
            actions.closePoolSettingsModal();
        }
    });
};

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    actions.initializeUI();
    utils.loadSelectedPool();
    utils.updateSelectedCount();
    
    // 获取默认按钮并检查是否可用
    const defaultBtn = document.querySelector('.number-btn[data-count="1"]');
    if (defaultBtn) {
        // 检查当前选中的学生数量
        const availableCount = state.selectedPool.size;
        // 找到第一个可用的按钮（数值不超过可用学生数）
        const firstAvailableBtn = Array.from(elements.numberBtns)
            .find(btn => parseInt(btn.dataset.count) <= availableCount);
            
        // 如果找到可用按钮，激活它
        if (firstAvailableBtn) {
            elements.numberBtns.forEach(btn => btn.classList.remove('active'));
            firstAvailableBtn.classList.add('active');
            state.selectedCount = parseInt(firstAvailableBtn.dataset.count);
        }
        
        actions.initializeSlotMachine();
    }
    setupEventListeners();
}); 